<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
    <link href="../../libs/mui.min.css" rel="stylesheet"/>
    <link href="../../libs/app.css" rel="stylesheet"/>
    <link href="../../css/main.css" rel="stylesheet"/>
    <link href="../../css/fill-in.css" rel="stylesheet"/>
    <style>
        .getPhoto {
            opacity: 0;
            width: 100%;
            height: 100%;
            position: absolute;
            display: block;
            top: 0;
        }

        .work-card > div, .left, .right {
            position: relative;
        }

        #fill_inphoto_1 {
            /*上传图片时用到的样式*/
            background-size: cover;
            background-repeat: no-repeat;
            background-position: center;
        }

    </style>
</head>

<body>
<div class="head">
    <img src="../../images/all-left.png" alt="" class="mui-action-back">
    <p>填写申请信息</p>
</div>
<div class="context">
    <div class="message">
        <div>
            <p>姓名</p>
            <input type="text" placeholder="" id="message-name">
        </div>
        <div>
            <p>身份证号码</p>
            <input type="text" placeholder="" id="id_card">
        </div>
        <div style="position: relative;" class="message-add">
            <p>所在区域</p>
            <div class="message-address" style="width: 60%;float: right;height: 100%;"></div>
            <div class="message-address-move">

            </div>
        </div>
        <div class="in-text">
            <p>请输入详细地址</p>
            <textarea placeholder="请输入详细地址" id="in-text-address" value=""></textarea>
        </div>
    </div>
    <div class="work-card">
        <div class="fill_in1photo" id="fill_inphoto_1"
             style="background-size: cover;background-repeat: no-repeat;background-position: center;">
            <img src="../../images/fill-jia.png">
            <p>上传工作证的图片（彩色）</p>
            <!--增加input-->
            <input type="file" class="getPhoto" onchange="FileReder_getphotos(this,'#fill_inphoto_1')"/>
            <!--<div id="preview">-->
            <!--</div>-->
        </div>
        <p>上传说明，必须拍摄清晰且完整的照片</p>
    </div>
    <div class="id-card">
        <div>
            <div class="left fill_in1photo" id="fill_inphoto_2"
                 style="background-size: cover;background-repeat: no-repeat;background-position: center;">
                <img src="../../images/fill-jia.png">
                <p>上传身份证正面的图片（彩色）</p>
                <!--增加input-->
                <input type="file" class="getPhoto" onchange="FileReder_getphotos(this,'#fill_inphoto_2')"/>
            </div>
            <div class="right fill_in1photo" id="fill_inphoto_3"
                 style="background-size: cover;background-repeat: no-repeat;background-position: center;">
                <img src="../../images/fill-jia.png">
                <p>上传身份证反面的图片（彩色）</p>
                <!--增加input-->
                <input type="file" class="getPhoto" onchange="FileReder_getphotos(this,'#fill_inphoto_3')"/>
            </div>

        </div>
        <p>上传说明，必须拍摄清晰且完整的照片</p>
    </div>
    <!--<div class="message">
        <div>
            <p>手机号码</p>
            <input type="text" placeholder="">
        </div>
    </div>
    <div class="yan">
        <div class="yan-input"><input type="text" placeholder="请输入验证码"></div>
        <div><button>获取验证码</button></div>
        <img src="../../images/yan.png" alt="">
    </div>-->
    <div class="button">
        <button id="submit-apply">提交申请</button>
    </div>
</div>

<div class="fill-in-picker"></div>
<script src="../../libs/mui.min.js"></script>
<script src="../../js/jquery-3.1.1.min.js"></script>
<script src="../../js/url.js"></script>
<!--<script src="../../js/fill-in_getphotos.js"></script>-->
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=AIEts6CoFGpdivbIz3uI3SrAG9iDB0Ko"></script>
<script src="../../js/location.js"></script>

<script>
    var imgBase64_1, imgBase64_2, imgBase64_3;

    // 经纬度
    getLocation_bd();

    $('.message-add').on('tap', function (e) {
        e.stopPropagation();
        sheng();
        $('.message-address-move').show(0);
        $('.fill-in-picker').show(0);
        $('.fill-in-picker').css('height', document.body.clientHeight);
        $('.message-address').css('borderLeft', '1px solid #ccc');
        $('body').css('overflow', 'hidden');
    })
    $('.fill-in-picker').on('tap', function () {
        $(this).hide(0);
        $('.message-address-move').hide(0);
        $('.message-address').css('borderLeft', 'none');
        $('body').css('overflow', 'auto');

    })

    // 省借口
    function sheng() {
        $('.message-address-move').children().remove();
        $.ajax({
            url: ur + 'rest/rcDistrictController/list/',
            headers: {
                "X-Token": localStorage.token
            },
            type: 'get',
            dataType: 'json',
            data: {
                "level": "1",
                "pId": "1"
            }
        })
            .done(function (data) {
                var i = data.data.length;
                for (var a = 0; a < i; a++) {
                    var li = $("<li class='message-address-move-li' id=" + data.data[a].id + ">" + data.data[a].name + "</li>");
                    $('.message-address-move').append(li);
                }
            })
    }
    // 市借口
    $('.message-address-move').on('tap', '.message-address-move-li', function (e) {
        e.stopPropagation();
        sessionStorage.p1 = $(this).attr('id');
        $('.message-address').text($(this).text());
        $.ajax({
            url: ur + '/rest/rcDistrictController/list/',
            headers: {
                "X-Token": localStorage.token
            },
            type: 'get',
            dataType: 'json',
            data: {
                "level": "2",
                "pId": sessionStorage.p1
            }
        })
            .done(function (data) {
                $('.message-address-move').children().remove();
                var i = data.data.length;
                for (var a = 0; a < i; a++) {
                    var li = $("<li class='message-address-move-li2' id=" + data.data[a].id + ">" + data.data[a].name + "</li>");
                    $('.message-address-move').append(li);
                }
            })
    })

    // 区借口
    $('.message-address-move').on('tap', '.message-address-move-li2', function (e) {
        e.stopPropagation();
        sessionStorage.p2 = $(this).attr('id');
        $('.message-address').text($('.message-address').text() + '-' + $(this).text());
        $.ajax({
            url: ur + '/rest/rcDistrictController/list/',
            headers: {
                "X-Token": localStorage.token
            },
            type: 'get',
            dataType: 'json',
            data: {
                "level": "3",
                "pId": sessionStorage.p2
            }
        })
            .done(function (data) {
                $('.message-address-move').children().remove();
                var i = data.data.length;
                for (var a = 0; a < i; a++) {
                    var li = $("<li class='message-address-move-li3' id=" + data.data[a].id + ">" + data.data[a].name + "</li>");
                    $('.message-address-move').append(li);
                }

            })
    })

    // 选择区
    $('.message-address-move').on('tap', '.message-address-move-li3', function (e) {
        e.stopPropagation();
        $('.message-address').text($('.message-address').text() + '-' + $(this).text());
        $('.fill-in-picker').hide(0);
        $('.message-address-move').hide(0);
        sessionStorage.p3 = $(this).attr('id');
        $('body').css('overflow', 'auto');
    })

    mui.init()

    //    function galleryImg() {
    //        FileReder_getphotos();
    //    }

    $(function () {
        var applyAgent = {};
        applyAgent.creat = function (agentData) {
            $.ajax({
                url: ur + 'rest/partnerController/create', // 添加代理商
                headers: {
                    "X-Token": localStorage.token
                },
                type: 'POST',
                dataType: 'json',
                data: agentData
            })
                .done(function (data) {
                    if (data.meta.code == 'S002') {
                        mui.toast('提交成功');
                        mui.back() //回首页
                    } else if (data.meta.code == 'E002') {
                        // mui.toast('你已经是代理商，请勿重新提交');
                        mui.toast(data.meta.message);
                    }
                });
        }
        applyAgent.update = function (agentData) {
            $.ajax({
                type: "post",
                url: ur + "rest/partnerController/update",
                async: true,
                headers: {
                    "X-Token": localStorage.token
                },
                dataType: 'json',
                data: agentData,
                success: function (data) {
                    if (data.meta.code == ERROR_OK) {
                        mui.toast('提交修改成功！');
                        mui.back();
                    } else {
                        mui.toast('提交修改失败！');
                    }
                }
            });
        }

        $.ajax({
            type: "get",
            url: ur + "rest/partnerController/getPartnerState", async: true, headers: {'X-Token': localStorage.token},
            dataType: 'json',
            success: function (data) {
                console.log(data);
                // 提交
                $('#submit-apply').on('tap', function () {
                    var imgUrl = function (id) {
                        var s = $(id).css('background-image').split('("')[1].split('")')[0];
                        return s.substring(s.indexOf(',') + 1, s.length); // 去除逗号及其前面的[1];
                    }
                    var idCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/
                    if ($('#message-name').val() == '') {
                        mui.toast('请填写姓名！')
                    } else if ($('#id_card').val() == '' || !idCard.test($('#id_card').val())) {
                        mui.toast('请检查身份证号码！')
                    } else if ($('#in-text-address').val() == '') {
                        mui.toast('请检查信息')
                    } else {
                        var agentData = {
                            address: sessionStorage.p3,
                            addressInfo: $('#in-text-address').val(),
                            bank: localStorage.bank,
                            idCardA: imgBase64_2,
                            idCardAFE: $('#fill_inphoto_2').attr('imgType'),
                            idCardB: imgBase64_3,
                            idCardBFE: $('#fill_inphoto_3').attr('imgType'),
                            idCardNumber: $('#id_card').val(),
                            realName: $('#message-name').val(),
                            type: localStorage.fillin_type,
                            workCard: imgBase64_1,
                            workCardFE: $('#fill_inphoto_1').attr('imgType'),
                            point: (localStorage.locationPoint ? localStorage.locationPoint : ''), // 坐标
                        };
                        console.log('agentData', agentData)
                        if (data.meta.code === 'S002') {
                            applyAgent.update(agentData);
                        } else {
                            applyAgent.creat(agentData);
                        }
                    }
                })

            },
            error: function (e) {
                mui.toast('数据请求错误，请重试');
            }
        });

    });

    function FileReder_getphotos(input, id) {
        var tapNum = id.replace('fill_inphoto_', '');

        if (typeof FileReader === 'undefined') {
            alert("抱歉，您的浏览器不支持FileReader")
        } else {
            readFile(input, id);
        }

        function readFile(input, id) {
            var imgName = input.files[0].name; // 图片完整名
            var imgType = judgeImg(imgName);
            if (imgType !== 'jpg' && imgType !== 'png') {
                mui.toast('请选择合法的图片');
                return false;
            }
            var baseType = input.files[0].type;
            $(id).attr('imgType', imgType);
            var file = input.files[0];
            if (!/image\/\w+/.test(file.type)) {
                alert("请确保文件为图像类型");
                return false;
            }
            var reader = new FileReader();
            /**
             * readAsDataURL方法会使用base-64进行编码，编码的资料由data字串开始，后面跟随的是MIME type，然后再加上base64字串，逗号之后就是编码过的图像文件的内容。
             */
            reader.readAsDataURL(file);//开始读取指定的Blob对象或File对象中的内容
            //读取成功后调用
            reader.onload = function (e) {
                // console.log(e.target.result);//获取File的url
                // alert(e.target.result);
                $(id + '>img').remove();
                $(id + '>p').remove();
                var imgPath = e.target.result; // base64
                $(id).css("background-image", "url(" + imgPath + ")");

                var imgData = imgPath.substring(imgPath.indexOf(',') + 1, imgPath.length);
                if (tapNum = '1') {
                    imgBase64_1 = imgData;
                } else if (tapNum = '2') {
                    imgBase64_2 = imgData;
                } else if (tapNum = '3') {
                    imgBase64_3 = imgData;
                }

                uploadHead(imgPath, baseType);
            };
            // 读取失败时调用
            reader.onerror = function (e) {
                console.log(JSON.stringify(e) + "出错");
            }
        }

        function judgeImg(path) {
            var regs = [/\.(gif|GIF)$/, /\.(jpg|JPG)$/, /\.(jpeg|JPEG)$/, /\.(png|PNG)$/];
            var type = ['gif', 'jpg', 'jpeg', 'png'];
            for (var i in regs) {
                if (regs[i].test(path)) {
                    return type[i];
                }
            }
        }
    }

    function uploadHead(imgPath, baseType) {
        var image = new Image();
        image.style.width = "100px";
        image.style.height = "100px";
        image.src = imgPath;
        image.onload = function () {
            var imgData = getBase64Image(image, baseType);
        }
    }

    function getBase64Image(img, baseType) {
        var canvas = document.createElement("canvas");
        var width = img.width;
        var height = img.height;
        canvas.width = width;
        /*设置新的图片的宽度*/
        canvas.height = height;
        /*设置新的图片的长度*/
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        /*绘图*/
        var dataURL = canvas.toDataURL(baseType, 0.1);
        return dataURL;
    }
</script>
</body>

</html>